package com.laowang.blog.provider;

import com.alibaba.fastjson.JSON;
import com.laowang.blog.dto.AccessTokenDto;
import com.laowang.blog.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GiteeProvider {
    public String getAccessToken(AccessTokenDto accessTokenDto){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDto));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code="+accessTokenDto.getCode()+"&client_id="+accessTokenDto.getClient_id()+"&redirect_uri="+accessTokenDto.getRedirect_url()+"&client_secret="+accessTokenDto.getClient_secret())
                .post(body)
                .build();
        try {
            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();
                String str1=string.split(":")[1];
                String str2 = str1.split("\"")[1];
                System.out.println("token+   "+str2);
                System.out.println(string);
                return str2;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public GiteeUser getUser(String Token){
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+Token)
                .build();

        try {
            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();
                GiteeUser user= JSON.parseObject(string, GiteeUser.class);
                return user;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
